package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Title: loginFilter
 * @Package com.itheima.reggie.filter
 * @Author: 🐟
 * @Copyright 🐟
 * @CreateTime: 2022/9/11 11:34
 */

@WebFilter
@Slf4j
public class loginFilter implements Filter {
    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("过滤器开启");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        String[] urls = {
                "/employee/login",
                "/employee/loginout",
                "/backend/**",
                "/front/**",
                "/user/login",
                "/user/sendMsg",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        for (String url : urls) {
            if (MATCHER.match(url, requestURI)) {
                filterChain.doFilter(request, response);
                return;
            }
        }
        //判断是否登录
        if (request.getSession().getAttribute("employee") != null||request.getSession().getAttribute("User") != null) {
            Long empId = (Long) request.getSession().getAttribute("employee");
            Long userId = (Long) request.getSession().getAttribute("User");

            if(empId!=null&&userId==null){
                BaseContext.setCurrentId(empId);
            }

            if(empId==null&&userId!=null){
                BaseContext.setCurrentId(userId);
            }


            filterChain.doFilter(request, response);
            BaseContext.remove();
        } else {
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    }
}
